package xl.com.controller;

import com.mysql.cj.x.protobuf.MysqlxExpr;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xl.com.model.ChatResponse;
import xl.com.model.Choice;
import xl.com.model.XLFunction;
import xl.com.model.XlMessage;
import xl.com.service.DeepSeekClient;
import xl.com.service.FunctionCallingService;
import xl.com.service.RAGService;


import java.util.*;

@RestController
@RequestMapping("/api/chat")
@RequiredArgsConstructor
public class ChatController {
    private final DeepSeekClient deepSeekClient;
    private final FunctionCallingService functionCallService;
    private final RAGService ragService;

    // 步骤5：更新控制器
    // 在原有chat方法中增加订单处理分支
    @PostMapping("/chatV2")
    public ResponseEntity<String> chat(String request) {
        // 增强的上下文检索
        String context = "";
        // 第一阶段：RAG检索增强
        if (containsOrderRelatedQuery(request)) {
            context = ragService.retrieveOrderInfo(request);
        } else {
            context = ragService.retrieveRelevantData(request);
        }

        // 后续处理逻辑保持不变...


        // 构建对话历史
        List<XlMessage> messages = new ArrayList<>();
        messages.add(new XlMessage("user", "以下是业务知识：" + context));
        messages.add(new XlMessage("user", request));
        XLFunction xlFunction = new XLFunction();
        // 定义可用函数
        XLFunction.ToolFunction toolFunctions =
                xlFunction.new ToolFunction(
                        "queryOrderData",
                        "查询指定订单相关信息",
                        Map.of(
                                "type", "object",
                                "order_id",
                                       Map.of("type",Map.of("description","订单号，如 123" ))
                        )
                )

        ;

        xlFunction.setFunction(toolFunctions);
        // 第二阶段：调用大模型
        Choice response = deepSeekClient.callChatAPI(messages, xlFunction);

        // 解析可能的函数调用（伪代码，需根据实际API响应结构调整）
        if (Objects.nonNull(response.getMessage().getRole().equals("assistant"))) {
            String result = functionCallService.handleFunctionCall(response.getMessage().getContent());

            // 第三阶段：带函数结果二次调用
            messages.add(new XlMessage("user", result));
            response = deepSeekClient.callChatAPI(messages,null);
            System.out.println(response);
        }

        return ResponseEntity.ok(response.getMessage().getContent());
    }

    private boolean containsOrderRelatedQuery(String question) {
        return question.matches(".*(订单|物流|退货|退款).*");
    }
    // 解析函数调用示例
    private MysqlxExpr.FunctionCall parseFunctionCall(String jsonResponse) {
//        JsonNode root = new ObjectMapper().readTree(jsonResponse);
//        JsonNode functionCall = root.path("choices").get(0).path("message").path("function_call");
//        return new MysqlxExpr.FunctionCall(
//                functionCall.path("name").asText(),
//                new ObjectMapper().convertValue(functionCall.path("parameters"), Map.class)
//        );
        return null;
    }

}
